package trace

import (
	"context"
	"crypto/tls"
	"log"
	"net/http"
	"net/http/httptrace"
	"time"
)

func TimeGet(url string, t time.Duration) map[string]interface{} {
	res := make(map[string]interface{})
	req, _ := http.NewRequest(http.MethodGet, url, nil)
	ctx, cancel := context.WithTimeout(context.Background(), t * time.Second)
	defer cancel()
	req = req.WithContext(ctx)
	var start, connect, dns, tlsHandshake time.Time

	trace := &httptrace.ClientTrace{
		GotConn: func(connInfo httptrace.GotConnInfo) {
			res["ip"] = connInfo.Conn.RemoteAddr()
		},
		DNSStart: func(dsi httptrace.DNSStartInfo) { dns = time.Now() },
		DNSDone: func(ddi httptrace.DNSDoneInfo) {
			res["dns"] = time.Since(dns).String()
		},

		TLSHandshakeStart: func() { tlsHandshake = time.Now() },
		TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
			res["tls"] = time.Since(tlsHandshake).String()
		},

		ConnectStart: func(network, addr string) { connect = time.Now() },
		ConnectDone: func(network, addr string, err error) {
			res["connect"] = time.Since(connect).String()
		},

		GotFirstResponseByte: func() {
			res["start_to_first"] = time.Since(start).String()
		},
	}

	req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
	start = time.Now()
	if _, err := http.DefaultTransport.RoundTrip(req); err != nil {
		log.Fatal(err)
		return map[string]interface{}{}
	}
	return res
}

